//package com.lagou.edu.wwyan.nacos.gateway.config;
//
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.server.reactive.ServerHttpRequest;
//import reactor.core.publisher.Mono;
//
//import java.net.InetAddress;
//import java.net.UnknownHostException;
//
//@Configuration
//@Slf4j
//public class KeyResolverConfig {
//    /**
//     * 根据请求ip进行限流
//     * @return
//     */
//    @Bean
//    public KeyResolver hostAddrKeyResolver(){
//        return exchange -> {
//            String ipAddr = getIpAddr(exchange.getRequest());
//            return Mono.just(ipAddr);
//        };
//    }
//    public  String getIpAddr(ServerHttpRequest request) {
//
//        HttpHeaders headers = request.getHeaders();
//        String ipAddress = headers.getFirst("X-Forwarded-For");
//        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
//            ipAddress = headers.getFirst("Proxy-Client-IP");
//        }
//        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
//            ipAddress = headers.getFirst("WL-Proxy-Client-IP");
//        }
//        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
//            ipAddress = request.getRemoteAddress().getAddress().getHostAddress();
//            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
//                // 根据网卡取本机配置的IP
//                try {
//                    InetAddress inet = InetAddress.getLocalHost();
//                    ipAddress = inet.getHostAddress();
//                } catch (UnknownHostException e) {
//                    log.error("根据网卡获取本机配置的IP异常", e);
//                }
//
//            }
//        }
//
//        // 对于通过多个代理的情况，第一个IP为客户端真实IP，多个IP按照','分割
//        if (ipAddress != null && ipAddress.indexOf(",") > 0) {
//            ipAddress = ipAddress.split(",")[0];
//        }
//
//        return ipAddress;
//    }
//}
